/*************************************************************************
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *
 *                COPYRIGHT (C) HONGLING CAPITAL CORPORATION 2012
 *    ALL RIGHTS RESERVED BY HONGLING CAPITAL CORPORATION. THIS PROGRAM
 * MUST BE USED  SOLELY FOR THE PURPOSE FOR WHICH IT WAS FURNISHED BY
 * HONGLING CAPITAL CORPORATION. NO PART OF THIS PROGRAM MAY BE REPRODUCED
 * OR DISCLOSED TO OTHERS,IN ANY FORM, WITHOUT THE PRIOR WRITTEN
 * PERMISSION OF HONGLING CAPITAL CORPORATION. USE OF COPYRIGHT NOTICE
 DOES NOT EVIDENCE PUBLICATION OF THE PROGRAM.
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *************************************************************************/

package com.springboot.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局统一异常处理类，用于拦截Controller的接口，比如当接口抛出异常时，可以被拦截，然后返回指定的报文（如错误信息、错误码）。
 *
 * @author hongchao zhao at 2019-4-24 15:19
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 定义全局异常捕获页面。
     */
    public static final String DEFAULT_ERROR_VIEW = "html/error/error";
    /**
     * 限流异常处理页面
     */
    public static final String RATE_LIMIT_ERROR_VIEW = "html/error/rateLimitError";

    /**
     * 捕获全局抛出异常。
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        LOG.debug("【全局异常】系统异常：【{}】。", e.getMessage());
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    /**
     * 捕获限流异常。
     */
    @ExceptionHandler(value = RateLimitException.class)
    public ModelAndView rateLimitErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        LOG.debug("【限流异常】当前系统请求超出限流次数：【{}】。", e.getMessage());
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", "亲，当前系统请求过于频繁，请稍后再试！");
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(RATE_LIMIT_ERROR_VIEW);
        return mav;
    }
}
